/****************************************************************
 * Homework 5 Main program
 * Author: Duncan Buell
 * Date last modified: 4 March 2010
 *
 * This main program drives a simplified simulation of process
 * management in an operating system.
 *
 * Input: none
 *
 * Output: only a log of what takes place
**/
#include "Main.h"

static const char TAG[] = "Main: ";
static const int MAXTIMEMINUSONE = 19; // no process can execute for
                                       // more than 20 timesteps

int main(int argc, char *argv[])
{
  long execTime;
  long finishTime;
  long pid;
  long startTime;
  long timeStep;
  Process localProcess;
  Scheduler scheduler;

  cout << TAG << "Beginning execution" << endl;

  srand(1);

//
// Fill the priority queue with process blocks.
//
  for(pid = 0; pid < 20; ++pid)
  {
// Note that we add one to make sure that all times are nonzero.
    startTime = (rand() % MAXTIMEMINUSONE) + 1;
    execTime = (rand() % MAXTIMEMINUSONE) + 1;
    finishTime = startTime + execTime;
    cout << TAG << "pid,start,exec,finish "
         << pid << " "
         << startTime << " "
         << execTime << " "
         << finishTime << endl;
    scheduler.addProcess(pid, startTime, execTime);
  }
  cout << TAG << "after all additions\n";
  cout << scheduler.toStringDump() << endl;

  
//
// Now run the simulation on timesteps.
//
  timeStep = 0;
  while(!scheduler.empty())
  {
        
    if(timeStep == scheduler.top().getFinishTime())
    {
      cout << TAG << "finishing at time " << timeStep << endl;
      while(timeStep == scheduler.top().getFinishTime())
      {
        
        localProcess = scheduler.top();
        cout << "     " << localProcess.toString() << endl;
        scheduler.pop();
      }
    }
    else
    {
      cout << TAG << "no processes finish at time " << timeStep << endl;
    }
    ++timeStep;
  }
  
  cout << TAG << "Ending execution" << endl;
  return 0;
}
